const moment = require('moment')
const crypto = require('crypto')
const qiniu = require('qiniu')

const config = think.config('qiniu')
if (config) {
  const {accessKey, secretKey, bucket} = config
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
  const putPolicy = new qiniu.rs.PutPolicy({
    scope: bucket,
    expires: 7200, // 两个小时授权一次
    // returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}'
    returnBody: '{"key":"$(key)","fsize":$(fsize)}'
  })
  const t = {}
  function auth () {
    if (t.timeOut && t.timeOut - Date.now() > 0) return // 定时任务 2个小时执行一次
    t.uploadToken = putPolicy.uploadToken(mac)
    t.config = new qiniu.conf.Config()
    t.formUploader = new qiniu.form_up.FormUploader(t.config)
    t.putExtra = new qiniu.form_up.PutExtra()
    t.timeOut = Date.now() + (7000000)
    t.bucketManager = new qiniu.rs.BucketManager(mac, t.config)
    // console.log(t)
  }

  // 服务器启动的时候执行一次
  auth()
  /**
   * 构造上传函数
   * @param key 服务器路径
   * @param localFile 本地路径
   * @returns {Promise}
   */
  function uploadFile (key, localFile) {
    auth()
    return new Promise((resolve, reject) => {
      t.formUploader.putFile(t.uploadToken, key, localFile, t.putExtra, function (respErr, respBody, respInfo) {
        if (respErr) {
          reject(respErr)
        }
        if (respInfo.statusCode === 200) {
          resolve(respBody)
        } else {
          yy.log.error(respInfo)
          reject(respInfo)
        }
      })
    })
  }
  /**
   * 删除图片
   * @param key 服务器路径
   * @returns {Promise}
   */
  function remove (key) {
    auth()
    return new Promise((resolve, reject) => {
      t.bucketManager.delete(bucket, key, function (err, respBody, respInfo) {
        if (err) {
          reject(err)
        } else {
          resolve({code: respInfo.statusCode})
        }
      })
    })
  }
  /**
   * md5
   * @param str
   * @returns {string|Buffer}
   */
  const md5 = function (str) {
    return crypto.createHash('md5').update(str).digest('hex')
  }

  /**
   * upload
   * 调用uploadFile上传
   * @param filePath 文件真实路径
   * @param group 分组信息
   */
  function upload (filePath, group = '') {
    // 上传到七牛后保存的文件名
    let key = moment().format('YYYYMMDDHHmmss') + md5(filePath)
    if (group) {
      key = `${group}-${key}`
    }
    return uploadFile(key, filePath)
  }

  module.exports = {
    upload, remove
  }
}
